/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package sn.dao;

import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

/**
 *
 * @author Pluce
 */
abstract public class GenericDAOImpl<T> implements GenericDAO<T> {
     
    @PersistenceContext(unitName="sn_tp")
    protected EntityManager em;
    
    private Class<T> clazz;
    
    public GenericDAOImpl(){
        clazz = this.entityClass();
    }
    
    /**
     * Doit être surchargée pour renvoyer le type de l'entité concernées
     * @return 
     */
    protected abstract Class<T> entityClass();

    @Override
    public T save(T entity) {
        return em.merge(entity);
    }

    @Override
    public void delete(T entity) {
        em.remove(em.merge(entity));
    }

    @Override
    public T findById(Long id) {
        return em.find(clazz, id);
    }

    @Override
    public List<T> findAll() {
        return (List<T>)em.createQuery("SELECT e FROM "+clazz.getSimpleName()+" e").getResultList();
    }
   
}
